<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="书名" prop="title">
        <el-input v-model="formData.title" placeholder="请输入书名" />
      </el-form-item>
      <el-form-item label="封面图片" prop="coverUrl">
        <UploadImg v-model="formData.coverUrl" />
      </el-form-item>
      <el-form-item label="语言" prop="language">
        <el-input v-model="formData.language" placeholder="请输入语言" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-input v-model="formData.category" placeholder="请输入分类" />
      </el-form-item>
      <el-form-item label="所属系列ID" prop="seriesId">
        <el-input v-model="formData.seriesId" placeholder="请输入所属系列ID" />
      </el-form-item>
      <el-form-item label="年级水平" prop="gradeLevel">
        <el-input v-model="formData.gradeLevel" placeholder="请输入年级水平（1-6）" />
      </el-form-item>
      <el-form-item label="难度等级" prop="difficulty">
        <el-input v-model="formData.difficulty" placeholder="请输入难度等级（1-5）" />
      </el-form-item>
      <el-form-item label="标签数组" prop="tags">
        <el-input v-model="formData.tags" placeholder="请输入标签数组（逗号分隔）" />
      </el-form-item>
      <el-form-item label="创建者" prop="creator">
        <el-input v-model="formData.creator" placeholder="请输入创建者" />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="formData.createTime"
          type="date"
          value-format="x"
          placeholder="选择创建时间"
        />
      </el-form-item>
      <el-form-item label="更新者" prop="updater">
        <el-input v-model="formData.updater" placeholder="请输入更新者" />
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker
          v-model="formData.updateTime"
          type="date"
          value-format="x"
          placeholder="选择更新时间"
        />
      </el-form-item>
      <el-form-item label="是否删除" prop="deleted">
        <el-radio-group v-model="formData.deleted">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { BookApi, Book } from '@/api/pickbook/book'

/** 绘本 表单 */
defineOptions({ name: 'BookForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  coverUrl: undefined,
  language: undefined,
  category: undefined,
  seriesId: undefined,
  gradeLevel: undefined,
  difficulty: undefined,
  tags: undefined,
  creator: undefined,
  createTime: undefined,
  updater: undefined,
  updateTime: undefined,
  deleted: undefined
})
const formRules = reactive({
  title: [{ required: true, message: '书名不能为空', trigger: 'blur' }],
  coverUrl: [{ required: true, message: '封面图片URL不能为空', trigger: 'blur' }],
  language: [{ required: true, message: '语言不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  seriesId: [{ required: true, message: '所属系列ID不能为空', trigger: 'blur' }],
  gradeLevel: [{ required: true, message: '年级水平（1-6）不能为空', trigger: 'blur' }],
  difficulty: [{ required: true, message: '难度等级（1-5）不能为空', trigger: 'blur' }],
  tags: [{ required: true, message: '标签数组（逗号分隔）不能为空', trigger: 'blur' }],
  creator: [{ required: true, message: '创建者不能为空', trigger: 'blur' }],
  updater: [{ required: true, message: '更新者不能为空', trigger: 'blur' }],
  updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await BookApi.getBook(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Book
    if (formType.value === 'create') {
      await BookApi.createBook(data)
      message.success(t('common.createSuccess'))
    } else {
      await BookApi.updateBook(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    coverUrl: undefined,
    language: undefined,
    category: undefined,
    seriesId: undefined,
    gradeLevel: undefined,
    difficulty: undefined,
    tags: undefined,
    creator: undefined,
    createTime: undefined,
    updater: undefined,
    updateTime: undefined,
    deleted: undefined
  }
  formRef.value?.resetFields()
}
</script>
